<template>
  <div>
    <!-- 引用组件 -->
    <Pivot
      ref="pivot"
      toolbar
      v-bind:report="report"
      v-bind:height="600"
      v-bind:shareReportConnection="{
        url: 'https://olap.flexmonster.com:9500',
      }"
      v-bind:beforetoolbarcreated="customizeToolbar"
      v-bind:customizeContextMenu="customizeContextMenu"
      _v-bind:licenseKey="'XXXX-XXXX-XXXX-XXXX-XXXX'"
      v-loading="loading"
    ></Pivot>
    <!-- 分页 -->
    <el-pagination
      style="margin-top:20px"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>
<script>
import cn from './translateCn.json';
export default {
  name: "PivotTableDemo",
  data () {
    return {
      loading: false,
      //分页
      currentPage: 1,
      pageSize: 10,
      total: 50,
      //配置
      report: {
        // 赋值
        "dataSource": {
          data: []
        },
        //汉化
        'localization': cn,
        //默认将布局设置为扁平方式 显示总计去掉
        options: {
          grid: { type: 'flat', showTotals: 'off', showGrandTotals: 'off' }
        }
      }
    }
  },
  mounted () {
    this.loadData()
  },
  methods: {
    //右键：自定义右键的按钮菜单
    customizeContextMenu (items, data, viewType) {
      //viewType 不同情况下的右击
      //viewType:pivot 布局：简洁方式和经典方式 网格
      //viewType:flat  布局：扁平方式 网格
      //viewType:charts charts图表右击
      //viewType:drillthrough 点钻取出现的网格（drill through view）然后再右键
      let that = this;
      if (viewType == "flat")
        items.push(
          {
            id: "custom-cell",
            label: "自定义右键:获取当前单元格数据",
            handler: function () {
              that.rightClickCell(data)
            }
          },
          {
            id: "custom-row",
            label: "自定义右键:获取当前一行数据",
            handler: function () {
              that.rightClickRow(data)
            }
          }
        );
      return items;
    },
    //自定义右键:获取当前单元格数据
    rightClickCell (data) {
      this.$message.success(data.label)
    },
    //自定义右键:获取当前一行数据 类似checkValue函数里面的方法取处理数据
    rightClickRow (data) {
      this.checkValue(data)
    },
    //获取数据
    loadData () {
      this.loading = true;
      this.report.dataSource.data = [
        { id: 1, 会计电子账簿编号: "94_2001", 会计年度: 2016, 会计月份: 2, 会计科目编码: "1004", 期初余额: Math.random() },
        { id: 2, 会计电子账簿编号: "94_2003", 会计年度: 2016, 会计月份: 2, 会计科目编码: "1007", 期初余额: Math.random() },
        { id: 3, 会计电子账簿编号: "94_2001", 会计年度: 2017, 会计月份: 4, 会计科目编码: "1008", 期初余额: Math.random() },
        { id: 4, 会计电子账簿编号: "94_2004", 会计年度: 2018, 会计月份: 7, 会计科目编码: "1004", 期初余额: Math.random() }
      ]
      setTimeout(() => {
        this.loading = false;
      }, 1000)
    },
    //pagesize改变
    handleSizeChange () {
      this.loadData()
    },
    //pageindex改变
    handleCurrentChange () {
      this.loadData()
    },
    //处理选中的疑点数据 
    //获取到所有的rowindex（去掉错误的和重复的） 再根据index找到当前行的数据
    checkValue (value) {
      //选中的单元格只有一个的时候是对象 多个是数组
      let indexArr = [], newIndexArr = [], trueArr = []
      if (!Array.isArray(value)) {
        value = [value]
      }
      value.map(item => {
        if (item.rowIndex <= this.report.dataSource.data.length) {
          indexArr.push(item.rowIndex)
        }
      })
      newIndexArr = Array.from(new Set(indexArr));
      trueArr = this.report.dataSource.data.filter((item, index) => {
        return newIndexArr.includes(index + 1)
      })
      this.$message.success('当前保存的疑点的数据是' + JSON.stringify(trueArr))
    },

    //保存疑点 获取到的当前表格选中的值 
    //通过取rowIndex获取到当前行的值
    saveDoubt () {
      let value = this.$refs.pivot.flexmonster.getSelectedCell();
      if (!value) return this.$message.warning('请先选择所需要保存的疑点数据');
      this.checkValue(value)
    },
    //保存配置 获取当前的配置 slice里面存的是columns rows measures
    saveFlexmonsterOptions () {
      let report = this.$refs.pivot.flexmonster.getReport();
      console.log(report)
      let slice = JSON.stringify(report.slice) || "{}"; // 字段配置
      let conditions = JSON.stringify(report.conditions) || "[]"; // 字段配置
      window.sessionStorage.setItem("slice", slice);
      window.sessionStorage.setItem("conditions", conditions);
      this.$message.success('当前配置已保存在缓存！');
    },
    //恢复存在session的配置
    setReport () {
      let report = this.$refs.pivot.flexmonster.getReport();
      let multidimensionalFields1 = window.sessionStorage.getItem("slice");
      let multidimensionalFields2 = window.sessionStorage.getItem("conditions");
      if (multidimensionalFields1 && multidimensionalFields2) {
        report.slice = JSON.parse(multidimensionalFields1);
        report.conditions = JSON.parse(multidimensionalFields2);
        this.$refs.pivot.flexmonster.setReport(report);
        this.$message.success('缓存中的配置已恢复！');

      } else {
        this.$message.warning('缓存中没有配置slice或者conditions！');
      }
    },
    //配置工具栏 加自己需要的按钮
    customizeToolbar (toolbar) {
      console.log(toolbar,toolbar.getTabs())
      let that = this
      var tabs = toolbar.getTabs();
      // delete tabs[0]; // 删除连接
      // delete tabs[1]; // 删除打开
      // delete tabs[2]; // 删除保存
      // delete tabs[3]; // 删除导出
      tabs.rightGroup=true
      toolbar.getTabs = function () {
        tabs.push({
          id: "fm-tab-connect",
          title: "保存疑点",
          handler: that.saveDoubt,
          icon: this.icons.save,
          // rightGroup :true,
        },
          {
            id: "fm-tab-connect",
            title: "保存配置",
            handler: that.saveFlexmonsterOptions,
            icon: this.icons.save,
                      // rightGroup :true,

          },
          {
            id: "fm-tab-connect",
            title: "恢复配置",
            handler: that.setReport,
            icon: this.icons.save,
                      // rightGroup :true,

          }
        );
        return tabs;
      }
    },
  },
};
</script>
